﻿using System;
using ITViet.Web.App_Code;
using System.Data;
using ITViet.Services;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Text;
using System.Web.UI.WebControls;
using System.IO;

namespace ITViet.Web.Controls
{
	public partial class SubMenu : BaseControl
	{
		#region Events
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack && !Page.IsCallback)
			{
				ShowMenu();
				LoadPageTitle();
				LoadProductTree();
			}

			if (Page.IsPostBack)
			{
				if (Request["__EVENTTARGET"] == "FrontLeftMenuChange")
				{
					string[] paras = Request["__EVENTARGUMENT"].Split('|');
					if (paras.Length >= 2)
					{
						SelectedSubMenuItem = paras[0];
						Response.Redirect(paras[1], false);
					}
				}
			}
		}
		#endregion

		#region Methods
		private void LoadProductTree()
		{
			string page = Path.GetFileName(Request.FilePath);
			switch (page)
			{
				case "ProductList.aspx":
					Literal ltrProductTree = Page.Master.FindControl("cphContentMain").FindControl("ltrProductTree") as Literal;
					if (ltrProductTree != null)
					{
						ltrProductTree.Text = LoadHierarchy();
					}
					break;
				case "ProductDetail.aspx":
					Literal ltrProductDetailTree = Page.Master.FindControl("cphContentMain").FindControl("ltrProductTree") as Literal;
					if (ltrProductDetailTree != null)
					{
						ltrProductDetailTree.Text = LoadHierarchy();
						ltrProductDetailTree.Text += string.Format(" » <a>{0}</a>", (Page as ITViet.Web.Pages.ProductDetail).ProductName);
					}
					break;
				default:
					break;
			}
		}

		private string LoadHierarchy()
		{
			StringBuilder hierarchy = new StringBuilder();
			for (int i = Hierarchy.Count - 1; i >= 0; i--)
			{
				if (i != Hierarchy.Count - 1)
				{
					hierarchy.Append(" » ");
				}

				hierarchy.Append(string.Format("<a href=\"ProductList.aspx?{0}\">{1}</a>", Hierarchy[i][0], Hierarchy[i][1]));
			}

			return hierarchy.ToString();
		}

		private void LoadPageTitle()
		{
			if (Page.Master != null)
			{
				Literal lrPageTitle = Page.Master.FindControl("lrPageTitle") as Literal;
				if (lrPageTitle != null)
				{
					if (lrPageTitle.Text == SelectedMenuItemTitle)
					{
						lrPageTitle.Text = SelectedSubMenuItemTitle;
					}
				}
			}
		}

		private void ShowMenu()
		{
			if (string.IsNullOrEmpty(SelectedMenuItem)) SelectedMenuItem = "0";
			subMenu.InnerHtml = "";

			SubMenuService menuService = new SubMenuService();
			DataSet ds = menuService.GetSubMenuByLanguage(Convert.ToInt32(SelectedMenuItem), CurrentLanguage.Id, null);
			if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
			{
				SelectedSubMenuItemTitle = SelectedMenuItemTitle;
				if (Page.Master != null)
				{
					Control divMenu = Page.Master.FindControl("submenu1") as Control;
					if (divMenu != null)
					{
						divMenu.Visible = false;
					}
				}
			}
			else
			{
				HttpContext currentContext = HttpContext.Current;
				string path = Request.Url.AbsolutePath;
				if (currentContext != null && currentContext.Items.Contains("HttpContextRewriteURL") && currentContext.Items["HttpContextRewriteURL"] != null)
				{
					path = currentContext.Items["HttpContextRewriteURL"].ToString();
				}

				string currentPage = path.Substring(path.LastIndexOf('/') + 1);
				if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
				{
					currentPage += "?" + Request.QueryString;
				}

				bool isParentActive = false;
				SelectedSubMenuItemTitle = SelectedMenuItemTitle;

				subMenu.InnerHtml += BuildSubMenu(ds.Tables[0], 0, currentPage, ref isParentActive);
			}
		}

		private string BuildSubMenu(DataTable table, int level, string currentPage, ref bool isParentActive)
		{
			StringBuilder result = new StringBuilder();
			bool isActive;
			level += 1;

			foreach (DataRow row1 in table.Rows)
			{
				string temp = string.Empty, row1Id = row1["Id"].ToString().Trim();
				if (row1Id == (Page as BasePage).TypeId.ToString() || row1["Link"].ToString().Trim() == currentPage)
				{
					isActive = true;
					SelectedSubMenuItem = row1Id;
					SelectedSubMenuItemTitle = row1["Title"].ToString();
				}
				else
				{
					isActive = false;
				}

				DataSet ds = new SubMenuService().GetSubMenuByParent(Convert.ToInt32(row1["Id"]), CurrentLanguage.Id, row1["Source"] != null ? row1["Source"].ToString() : "");
				if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
				{
					temp = BuildSubMenu(ds.Tables[0], level, currentPage, ref isActive);
				}

				string classCss = string.Empty;
				if (table.Rows.IndexOf(row1) == table.Rows.Count - 1 && level == 1)
				{
					classCss = "last ";
				}

				if (isActive)
				{
					Hierarchy.Add(new string[] { string.Format("tid={0}", row1Id), row1["Title"].ToString() });
					isParentActive = true;
					classCss += isActive ? "active" : string.Empty;
				}

				string onclick = string.Format("onclick=\"showDetail(jQuery(this), '{0}','{1}')\"", row1["Id"], row1["Link"]);
				string address = Address(row1["Id"].ToString(), row1["Link"].ToString(), row1["Title"].ToString(), row1["Title"].ToString(), onclick);

				if (!string.IsNullOrEmpty(temp))
				{
					result.Append(string.Format("<li class=\"{0}\">{1}<ul{2}>{3}</ul></li>", classCss, address, isActive ? string.Empty : " style=\"display:none\"", temp));
				}
				else
				{
					result.Append(string.Format("<li class=\"{0}\">{1}</li>", classCss, address));
				}
			}

			return result.ToString();
		}

		private string Address(string id, string href, string title, string text, string onclick)
		{
			string target = string.Empty;
			if (!string.IsNullOrEmpty(href))
			{
				if (Uri.IsWellFormedUriString(href, UriKind.Absolute))
				{
					Uri url = new Uri(href);
					if (url.Host != Request.Url.Host)
					{
						target = "target=\"_blank\" ";
					}
				}
			}

			return string.Format("<a id=\"{0}\" title=\"{1}\" href=\"javascript:void(0)\" {2} {3}>{4}</a>", id, title, onclick, target, text);
		}
		#endregion
	}
}